const dataBase = require('../../mysql')

const sql = require('../../mysql/sql')
const verifyRequestMethod = require('../../tool/verifyRequestMethod')
const config = require('../../config')

/**
 * @description 文章详情
 */
module.exports = function () {
    const that = this
    /**
     * @description 获取query
     * @type {{}|*}
     */
    const query = this.getQueryData(this.request.url)
    /**
     * @description 请求验证
     */
    verifyRequestMethod(this.request, 'GET').then(function () {
        if (isNaN(parseInt(query.articleId))) {
            return Promise.reject(new Error('缺少文章Id！'))
        } else {
            return Promise.resolve()
        }
    }).then(function () {
        /**
         * @description 验证文章ID
         */
        return dataBase.connect(sql.SQL_SELECT_ARTICLE_ONE(query.articleId, config.USE_QUERY_NORMAL_ARTICLE)).then(function (result) {
            if (that.isUnDef(result[0])) {
                return Promise.reject(new Error('无效的文章Id！'))
            } else {
                return Promise.resolve(result[0])
            }
        }).catch(function () {
            return Promise.reject(new Error('无效的文章Id！'))
        })
    }).then(function (result) {
        /**
         * @description 当前文章
         */
        const currentArticle = result
        /**
         * @description 统计预览次数
         * @type {number}
         */
        let previewTotal = 0
        /**
         * @description 是否是新的文章?
         */
        if (currentArticle.previewTotal !== null) {
            previewTotal = parseInt(currentArticle.previewTotal)
        }
        /**
         * @description 统计累计
         */
        previewTotal++
        /**
         * @description 更新
         */
        return dataBase.connect(sql.SQL_UPDATE_ARTICLE_PREVIEW_TOTAL(previewTotal, query.articleId))
    }).then(function () {
        /**
         * @description 查询文章
         */
        return dataBase.connect(sql.SQL_SELECT_ARTICLE_ONE_DETAIL(query.articleId))
    }).then(function (result) {
        /**
         * @description 返回数据
         */
        that.response.outPrintData(result[0], '查询成功！')
    }).catch(function (e) {
        that.response.outPrintError((e && e.message) || '未知错误！')
    })
}